package com.yzd.netmonitor.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 系统安全加密工具类. 提供MD5 、SHA加密算法操作.
 * Encryption：加密
 *
 */
public final class EncryptionHelper {

	//盐
	private static final String salt = "y3r3j3";

	/**
	 * 复杂的加密算法.
	 * @param password
	 * @return
	 */
	public static final String encrypt(String password) {
		String rootValue = Base64.encode(password + salt);
		String md5 = md5(sha(rootValue));

		String target = null;
		for (int i = 0; i < 4; i++) {
			target = md5(md5);
		}
		target = sha(target).substring(2, 37);
		return target;
	}

	/**
	 * MD5加密算法.
	 * @param plainText
	 * @return
	 */
	public static String md5(final String plainText) {
		String result = plainText;
		try {
			final MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(plainText.getBytes());
			final byte b[] = md.digest();
			int i;
			final StringBuffer buf = new StringBuffer("");
			for (int offset = 0; offset < b.length; offset++) {
				i = b[offset];
				if (i < 0)
					i += 256;
				if (i < 16)
					buf.append("0");
				buf.append(Integer.toHexString(i));
			}
			result = buf.toString();
			//System.out.println("result: " + buf.toString());//32位的加密 
			//System.out.println("result: " + buf.toString().substring(8, 24));//16位的加密 
		} catch (final NoSuchAlgorithmException e) {
		}
		return result;
	}

	/**
	 * Sha加密算法.
	 * @param plainText
	 * @return
	 */
	public static String sha(final String plainText) {
		String str = "";
		String tempStr = "";
		try {
			final MessageDigest md = MessageDigest.getInstance("SHA-1");//SHA-1
			final byte[] digest = md.digest(plainText.getBytes());

			for (int index = 0; index < digest.length; index++) {
				tempStr = (Integer.toHexString(digest[index] & 0xff));
				if (tempStr.length() == 1) {
					str = str + "0" + tempStr;
				} else {
					str = str + tempStr;
				}
			}
		} catch (final NoSuchAlgorithmException e) {
		}
		return str;
	}

	private EncryptionHelper() {
		throw new AssertionError("Uninstantiable class.");
	}
}
